package awdc;

import java.util.concurrent.*;

class Hub {
	HubParametrs Params;
	Hub Next;
	Speaker Speak;
	NickList Nicks;
	Shara HShara;
	//Disp Dispatcher;
	ExecutorService Executor;
	boolean IsConnected;

	//Конструктор
	Hub (HubParametrs Params){
		this.Params = Params;
		HShara = new Shara(Params.getSharedDirectory(),"filelist");
		IsConnected = false;
	}

	//Метод, выводящий на экран параметры хаба
	public void showHub(){
		System.out.println("Hub info:");
		System.out.println("Address:\t\t" + this.getAddress()+":"+this.getPort());
		System.out.println("Nick for this hub:\t"+this.getNick());
		System.out.println("Is connected:\t\t"+this.getIsConnected());
	}
	//Метод, возвращающий адрес
	String getAddress(){
		return this.Params.getAddress();
	}
	//Метод, возвращающий ник
	String getNick(){
		return this.Params.getNick();
	}

	int getPort(){
		return this.Params.getPort();
	}

	//Метод залогинивания
	void login (){
		System.out.println("Trying to connect to hub");
		if (!this.IsConnected){
			Speak = new Speaker();
			if (Speak.connect(Params.getAddress(), Params.getPort())==0) {
				byte[] Inline = Speak.receive();
				//Нижняя строчка закомментирована до тех пор, пока ниче не поддерживаем))
				//String ToSend = "$Supports UserIP UserCommand|$Key bla-bla|$ValidateNick "+this.getNick()+"|";
				String ToSend = "$Key bla-bla|$ValidateNick "+this.getNick()+"|";
				

				Speak.send(ToSend);
				Inline = Speak.receive();
				Speak.send("$Version 1,0091|$MyINFO $ALL "+this.getNick()+" <++ V:0.698,M:P,H:1/0/0,S:1>$ $0.005$$0$|$GetNickList|");
				//Speak.send("$Version 1,0091|$GetNickList|$MyINFO $ALL "+this.getNick()+" <++ V:0.698,M:P,H:1/0/0,S:1>$ $0.005$$0$|");
				Speak.receive();
				IsConnected = true;
			} else
				IsConnected = false;
			if (IsConnected){
				Executor = Executors.newFixedThreadPool(5);
				Executor.execute(new Disp(Speak,Executor,Nicks,HShara));
			}
		} else 
			System.out.println("Already connected");
	}
	//Метод, выводящий из коннектед
	boolean getIsConnected(){
		return IsConnected;
	}

}
